package com.xjc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.AllStudentRegsiterRelations;
import com.xjc.business.entity.domain.ClassAdminRelations;
import com.xjc.business.entity.domain.WxUser;
import com.xjc.business.entity.po.ChatMsgPo;
import com.xjc.business.entity.vo.classadmin.ChatMsgContainer;
import com.xjc.business.entity.vo.stu.ClassAdminInfoVo;
import com.xjc.business.service.*;
import com.xjc.business.entity.domain.ChatMsg;
import com.xjc.business.mapper.ChatMsgMapper;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
* @author root
* @description 针对表【chat_msg(聊天消息表)】的数据库操作Service实现
* @createDate 2025-02-14 15:42:09
*/
@Service
public class ChatMsgServiceImpl extends ServiceImpl<ChatMsgMapper, ChatMsg>
    implements ChatMsgService {

    @Autowired
    @Lazy
    WxUserService wxUserService;

    @Autowired
    @Lazy
    StudentsService studentsService;

    @Autowired
    @Lazy
    AllStudentRegsiterRelationsService allStudentRegsiterRelationsService;

    @Autowired
    @Lazy
    ClassAdminRelationsService classAdminRelationsService;

    @Autowired
    @Lazy
    ClassAdminsService classAdminsService;

    /**
     * 改变消息状态
     *
     * @param msgId
     * @param msgHasRead
     */
    @Override
    public void updateMsgStatusById(List<Integer> msgId, Integer msgHasRead) {
        LambdaQueryWrapper<ChatMsg> sysMsgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysMsgLambdaQueryWrapper.in(ChatMsg::getId,msgId);
        List<ChatMsg> chatMsgList = list(sysMsgLambdaQueryWrapper).stream().map(item -> {
            item.setReadStatus(msgHasRead);
            return item;
        }).collect(Collectors.toList());
        updateBatchById(chatMsgList);
    }

    /**
     * 获取聊天消息列表
     *
     * @param classAdminIdKey 辅导员id
     * @return 数据
     */
    @Override
    public Result<List<ChatMsgContainer>> getChatMsgContainer(String classAdminIdKey) {
        LambdaQueryWrapper<ChatMsg> sysMsgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysMsgLambdaQueryWrapper.eq(ChatMsg::getSendId,classAdminIdKey).or().eq(ChatMsg::getReviceId,classAdminIdKey);
        sysMsgLambdaQueryWrapper.orderByAsc(ChatMsg::getCreateTime);

        Map<String, List<ChatMsg>> collect = list(sysMsgLambdaQueryWrapper).stream().collect(Collectors.groupingBy(ChatMsg::getSessionId)); //分组

        List<ChatMsgContainer> chatMsgContainerList = new ArrayList<>();

        for (Map.Entry<String, List<ChatMsg>> entry : collect.entrySet()) {
            ChatMsgContainer chatMsgContainer = new ChatMsgContainer();

            String sessionId = entry.getKey();

            String wxId = sessionId.split("-")[0].split(":")[1];
            WxUser wxUser = wxUserService.getById(wxId);
            Integer stuId = wxUser.getStuId();
            String pic = wxUser.getPic();
            String stuName = studentsService.getById(stuId).getName();

            List<Integer> unReadMsgIdList = new ArrayList<>();
            AtomicReference<Integer> unReadNum = new AtomicReference<>(0);

            chatMsgContainer.setStuId(Integer.valueOf(wxId));
            chatMsgContainer.setStuName(stuName);
            chatMsgContainer.setPic(pic);

            List<ChatMsgPo> chatMsgList = entry.getValue().
                    stream().
                    sorted((o1, o2) -> o1.getCreateTime().compareTo(o2.getCreateTime())).
                    map(item -> {
                        ChatMsgPo chatMsg = new ChatMsgPo();
                        if (item.getReviceId().equals(classAdminIdKey) && Objects.equals(item.getReadStatus(), MyConstants.MSG_NOT_READ)){
                            unReadMsgIdList.add(item.getId());
                            unReadNum.getAndSet(unReadNum.get() + 1);
                        }
                        chatMsg.setSendId(item.getSendId());
                        chatMsg.setReviceId(item.getReviceId());
                        chatMsg.setMsg(item.getMsg());
                        chatMsg.setPic(item.getPic());
                        chatMsg.setFile(item.getFile());
                        chatMsg.setVideo(item.getVideo());
                        chatMsg.setIcon(item.getIcon());
                        chatMsg.setType(item.getType());
                        chatMsg.setReadStatus(item.getReadStatus());
                        chatMsg.setCreateTime(item.getCreateTime());
                        return chatMsg;
                    }).
                    collect(Collectors.toList());//排序

            chatMsgContainer.setUnReadMsgIdList(unReadMsgIdList);
            chatMsgContainer.setUnReadNum(unReadNum.get());
            chatMsgContainer.setChatMsgList(chatMsgList);

            chatMsgContainerList.add(chatMsgContainer);
        }

        chatMsgContainerList.sort((o1, o2) -> o2.getUnReadNum().compareTo(o1.getUnReadNum())); //按照未读消息数量排序

        return Result.okWithData(chatMsgContainerList);
    }

    /**
     * 获取聊天消息
     * @param wxIdKey 微信id
     * @return 数据
     */
    @Override
    public Result<ChatMsgContainer> getStuChatMsgContainer(String wxIdKey) {
        LambdaQueryWrapper<ChatMsg> sysMsgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysMsgLambdaQueryWrapper.eq(ChatMsg::getSendId,wxIdKey).or().eq(ChatMsg::getReviceId,wxIdKey);
        sysMsgLambdaQueryWrapper.orderByAsc(ChatMsg::getCreateTime);

        ChatMsgContainer chatMsgContainer = new ChatMsgContainer();

        List<Integer> unReadMsgIdList = new ArrayList<>();
        AtomicReference<Integer> unReadNum = new AtomicReference<>(0);

        List<ChatMsgPo> chatMsgPoList = list(sysMsgLambdaQueryWrapper).stream().map(item -> {
            ChatMsgPo chatMsg = new ChatMsgPo();
            if (item.getReviceId() == wxIdKey && item.getReadStatus() == MyConstants.MSG_NOT_READ) {
                unReadMsgIdList.add(item.getId());
                unReadNum.getAndSet(unReadNum.get() + 1);
            }
            chatMsg.setSendId(item.getSendId());
            chatMsg.setReviceId(item.getReviceId());
            chatMsg.setMsg(item.getMsg());
            chatMsg.setPic(item.getPic());
            chatMsg.setFile(item.getFile());
            chatMsg.setVideo(item.getVideo());
            chatMsg.setIcon(item.getIcon());
            chatMsg.setType(item.getType());
            chatMsg.setReadStatus(item.getReadStatus());
            chatMsg.setCreateTime(item.getCreateTime());
            chatMsg.setUpdateTime(item.getUpdateTime());
            return chatMsg;
        }).collect(Collectors.toList());

        chatMsgContainer.setUnReadMsgIdList(unReadMsgIdList);
        chatMsgContainer.setUnReadNum(unReadNum.get());
        chatMsgContainer.setChatMsgList(chatMsgPoList);

        return Result.okWithData(chatMsgContainer);
    }

    /**
     * 获取班级管理员名称
     * @param wxId 微信id
     * @return 数据
     */
    @Override
    public Result<ClassAdminInfoVo> getClassAdminName(String wxId) {

        Integer stuId = wxUserService.getById(wxId).getStuId();

        LambdaQueryWrapper<AllStudentRegsiterRelations> allStudentRegsiterRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        allStudentRegsiterRelationsLambdaQueryWrapper.eq(AllStudentRegsiterRelations::getStuId,stuId);
        AllStudentRegsiterRelations studentFromDB = allStudentRegsiterRelationsService.getOne(allStudentRegsiterRelationsLambdaQueryWrapper);
        Integer clazzId = studentFromDB.getClazzId();


        LambdaQueryWrapper<ClassAdminRelations> classAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        classAdminRelationsLambdaQueryWrapper.eq(ClassAdminRelations::getClId,clazzId);
        ClassAdminRelations classAdminRelations = classAdminRelationsService.getOne(classAdminRelationsLambdaQueryWrapper);
        Integer clazzAdminId = classAdminRelations.getClazzAdminId();

        String nickname = classAdminsService.getById(clazzAdminId).getNickname();

        ClassAdminInfoVo classAdminInfoVo = new ClassAdminInfoVo();
        classAdminInfoVo.setStuName(nickname);
        classAdminInfoVo.setClassAdminId(clazzAdminId);

        return Result.okWithData(classAdminInfoVo);
    }

    @Override
    public Long getMessageNumWithSessionId(String sessionId) {
        LambdaQueryWrapper<ChatMsg> chatMsgLambdaQueryWrapper = new LambdaQueryWrapper<>();
        chatMsgLambdaQueryWrapper.eq(ChatMsg::getSessionId,sessionId);
        return count(chatMsgLambdaQueryWrapper);
    }

    @Override
    public ChatMsgContainer getWholeMsg(String wxId) {
        WxUser wxUser = wxUserService.getById(wxId);
        Integer stuId = wxUser.getStuId();
        String pic = wxUser.getPic();
        String stuName = studentsService.getById(stuId).getName();

        ChatMsgContainer chatMsgContainer =new ChatMsgContainer();
        chatMsgContainer.setStuName(stuName);
        chatMsgContainer.setStuId(wxUser.getId());
        chatMsgContainer.setPic(pic);

        return chatMsgContainer;
    }
}




